package com.example.base.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.example.base.loadsir.EmptyCallback;
import com.example.base.loadsir.ErrorCallback;
import com.example.base.loadsir.LoadingCallback;
import com.example.base.viewmodel.MvvmBaseViewModel;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

public abstract class MvvmActivity<V extends ViewDataBinding,VM extends MvvmBaseViewModel> extends AppCompatActivity implements IBaseView{
    protected VM viewModel;
    protected V viewDataBinding;
    protected LoadService mLoadService;

    /**
     * @return 布局的layoutId
     */
    @LayoutRes
    public abstract  int getLayoutId();
    protected abstract VM getViewModel();
    public abstract int getBindingVariable();

    /**
     * 请求失败时，重试
     */
    protected abstract void onRetryClick();

    /**
     * 加载页面
     */
    @Override
    public void showContent() {
        if(mLoadService != null){
            mLoadService.showSuccess();
        }
    }

    /**
     * 显示Loading
     */
    @Override
    public void showLoading() {
        if(mLoadService != null) {
            mLoadService.showCallback(LoadingCallback.class);
        }
    }

    /**
     * 空页面显示
     */
    @Override
    public void onRefreshEmpty() {
        if(mLoadService != null) {
            mLoadService.showCallback(EmptyCallback.class);
        }
    }

    /**
     * 失败页面显示
     * @param message 失败的message
     */
    @Override
    public void onRefreshFailure(String message) {
        if(mLoadService != null){
            mLoadService.showCallback(ErrorCallback.class);
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        performDataBinding();
    }

    /**
     * 设置加载中(loading)，重试(retry)和无数据(empty)等页面
     * @param view 要替换的View
     */
    public void setLoadSir(View view){
        //You can change the callback on sub thread directly
        mLoadService = LoadSir.getDefault().register(view, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                //重试
                onRetryClick();
            }
        });
    }

    /**
     * 数据绑定
     */
    private void performDataBinding(){
        viewDataBinding = DataBindingUtil.setContentView(this,getLayoutId());
        if(viewModel == null){
            this.viewModel = getViewModel();
        }
        if(getBindingVariable() > 0) {
            viewDataBinding.setVariable(getBindingVariable(),viewModel);
        }
        viewDataBinding.executePendingBindings();
    }
}
